/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PanInputUserMathExpression.java
 *
 * Created on 31-jul-2011, 10:52:57
 */

package br.usp.ime.faguilar.guis.capturers;

import DatabaseMathExpressions.DBFuntions;
import DatabaseMathExpressions.ModelExpression;
import DatabaseMathExpressions.UserExpression;
import br.usp.ime.faguilar.guis.PanManageUserExpressions;
import br.usp.ime.faguilar.guis.MathExpressionDrawing.Panels.PanWriting;
import Matching.ExpressionMatching;
import Matching.Matching;
import MathExpression.Data.DMathExpression;
import MathExpression.Graphics.GMathExpression;
import Util.Util;
import java.sql.Timestamp;
import java.util.Calendar;
import javax.swing.JDialog;
import javax.swing.JOptionPane;

/**
 *
 * @author frank
 */
public class PanInputUserMathExpression extends javax.swing.JPanel {
     private ModelExpression selectedMExpression;
     private DBFuntions dbFunctions;
     private String myUser;

     private Matching matching;

     private boolean completeInput;

    /** Creates new form PanInputUserMathExpression */
    public PanInputUserMathExpression() {
        initComponents();
        initializeAllFields();
    }

    private void initializeAllFields(){
        selectedMExpression=null;
        matching=new ExpressionMatching();
        this.setVisibleLabelingButton(false);
        myUser="";
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane2 = new javax.swing.JSplitPane();
        panControlInputMathExpressions1 = new br.usp.ime.faguilar.guis.capturers.PanControlInputMathExpressions();
        jScrollPane1 = new javax.swing.JScrollPane();
        panImageOfModel = new br.usp.ime.faguilar.guis.MathExpressionDrawing.Panels.PanNotEditableNamedMathExpression();
        jPanel1 = new javax.swing.JPanel();
        jButSaveExpression = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        lblTotalOfInputExpressions = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setLayout(new java.awt.BorderLayout());

        jSplitPane2.setDividerLocation(200);
        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane2.setPreferredSize(new java.awt.Dimension(627, 600));
        jSplitPane2.setRightComponent(panControlInputMathExpressions1);

        panImageOfModel.setPreferredSize(new java.awt.Dimension(20, 20));

        org.jdesktop.layout.GroupLayout panImageOfModelLayout = new org.jdesktop.layout.GroupLayout(panImageOfModel);
        panImageOfModel.setLayout(panImageOfModelLayout);
        panImageOfModelLayout.setHorizontalGroup(
            panImageOfModelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 672, Short.MAX_VALUE)
        );
        panImageOfModelLayout.setVerticalGroup(
            panImageOfModelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 194, Short.MAX_VALUE)
        );

        jScrollPane1.setViewportView(panImageOfModel);

        jSplitPane2.setLeftComponent(jScrollPane1);

        add(jSplitPane2, java.awt.BorderLayout.CENTER);

        jPanel1.setPreferredSize(new java.awt.Dimension(517, 46));

        jButSaveExpression.setText("Save");
        jButSaveExpression.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButSaveExpressionMouseClicked(evt);
            }
        });

        jProgressBar1.setStringPainted(true);

        lblTotalOfInputExpressions.setText("Written expressions:");

        jButton1.setText("My expressions");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(lblTotalOfInputExpressions, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 149, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jProgressBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(59, 59, 59)
                .add(jButton1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 62, Short.MAX_VALUE)
                .add(jButSaveExpression)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jProgressBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, lblTotalOfInputExpressions, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton1)
                        .add(jButSaveExpression)))
                .addContainerGap())
        );

        add(jPanel1, java.awt.BorderLayout.PAGE_END);
    }// </editor-fold>//GEN-END:initComponents

    public void upDateAdvance(){
        int[] advance=dbFunctions.getAdvanceUfUser(myUser);
        String AdvanceText=advance[0]+" of "+advance[1];
        if(advance[0]==advance[1]){
            setCompleteInput(true);
            this.panControlInputMathExpressions1.setEnabled(false);
            this.jButSaveExpression.setEnabled(false);
            panImageOfModel.setModelName("");
            panImageOfModel.setDrawable(null);
            this.panImageOfModel.repaint();
        }else{
            chargeModel();
            setCompleteInput(false);
            this.panControlInputMathExpressions1.setEnabled(true);
            this.jButSaveExpression.setEnabled(true);
        }
        this.jProgressBar1.setValue(advance[0]);
        jProgressBar1.setMaximum(advance[1]);
        jProgressBar1.setString(AdvanceText);
    }
    
    private void chargeModel(){
//        TO CHARGE MODELS ORDERED BY THEIR ID
//        ArrayList<ModelExpression> modelExpr=dbFunctions.getModelsForUser(myUser);
//        if(!modelExpr.isEmpty()){
//            selectedMExpression=modelExpr.get(0);
//            ((GMathExpression)selectedMExpression.getdMathExpression()).showJustMathExpression();
//            panImageOfModel.setModelName("Model "+selectedMExpression.getId());
//            panImageOfModel.setDrawable((GMathExpression)selectedMExpression.getdMathExpression());
//        }
//        TO CHARGE MODELS RAMDONLY
        ModelExpression modelExpr=dbFunctions.getModelForUserRandomly(myUser);
        if(modelExpr!=null){
            selectedMExpression=modelExpr;
            ((GMathExpression)selectedMExpression.getdMathExpression()).showJustMathExpression();
            panImageOfModel.setModelName("Model "+selectedMExpression.getId());
            panImageOfModel.setDrawable((GMathExpression)selectedMExpression.getdMathExpression());
        }
        this.panImageOfModel.repaint();
    }

    private void jButSaveExpressionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButSaveExpressionMouseClicked
        // TODO add your handling code here:
        if(!isCompleteInput()){
             DMathExpression dmeModel= this.selectedMExpression.getdMathExpression();

            if(mathExpressionWithCorrectNumberOfSymbols()){
                DMathExpression dmeUser=this.panControlInputMathExpressions1.getGMathExpression();

                String [][] match=this.matching.match(dmeModel, dmeUser);

                int[][] matchInt=Util.stringToIntMatrix(match);
                String time=Calendar.getInstance().getTime().toString();
                UserExpression ue=new UserExpression(null, selectedMExpression.getId(),time, matchInt);
                ue.setdMExpression((DMathExpression) dmeUser.clone());
                Timestamp date=new Timestamp(Calendar.getInstance().getTime().getTime());
                ue.setTimeStampInput(date);
                ue.setIdUser(myUser);

                int index=dbFunctions.getMaxIdUserExpression(myUser);
                ue.setId(index+1);
                dbFunctions.addUserExpressions(ue);

                this.panControlInputMathExpressions1.clearPanel();
    //            this.chargeModel();
                this.upDateAdvance();
            }else{
                JOptionPane.showMessageDialog(this,"Number of symbols are supposed to be: "+dmeModel.size(),"Incorrect number of symbols",
                                JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jButSaveExpressionMouseClicked

    private boolean mathExpressionWithCorrectNumberOfSymbols(){
        DMathExpression mathModelExpression= this.selectedMExpression.getdMathExpression();
        DMathExpression mathUserExpression=this.panControlInputMathExpressions1.getGMathExpression();
        if(mathModelExpression.size()==mathUserExpression.size())
            return true;
        return false;
    }

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        // TODO add your handling code here:
        JDialog jd=new JDialog();
        PanManageUserExpressions pmue=new PanManageUserExpressions();
        pmue.setDbFunctions(dbFunctions);
        pmue.setMyUser(myUser);
        pmue.chargeMyUserExpressions();
        pmue.setPanUpdateAdvance(this);
        jd.setContentPane(pmue);
        jd.pack();
        jd.setModal(true);
        jd.setVisible(true);
    }//GEN-LAST:event_jButton1MouseClicked

    public void setVisibleLabelingButton(boolean visible){
        this.panControlInputMathExpressions1.setVisibleLabelingButton(visible);
    }

    public String getMyUser() {
        return myUser;
    }

    public void setMyUser(String myUser) {
        this.myUser = myUser;
    }

    public DBFuntions getDbFunctions() {
        return dbFunctions;
    }

    public void setDbFunctions(DBFuntions dbFunctions) {
        this.dbFunctions = dbFunctions;
    }

    public boolean isCompleteInput() {
        return completeInput;
    }

    public void setCompleteInput(boolean completeInput) {
        this.completeInput = completeInput;
    }

    public PanWriting getPanWriting(){
        return panControlInputMathExpressions1.getPanWriting();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButSaveExpression;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JLabel lblTotalOfInputExpressions;
    private br.usp.ime.faguilar.guis.capturers.PanControlInputMathExpressions panControlInputMathExpressions1;
    private br.usp.ime.faguilar.guis.MathExpressionDrawing.Panels.PanNotEditableNamedMathExpression panImageOfModel;
    // End of variables declaration//GEN-END:variables
}
